import React, { useState } from "react";
import { useNavigate } from "react-router-dom";
import useSWR from "swr";
import { fetcher } from "../utils";
import "./course.css";

function ClassNew(props) {
    const navigate = useNavigate();
    const { data: courseList } = useSWR("/api/course/list", fetcher);
    const safeCourseList = Array.isArray(courseList) ? courseList : [];
    const [name, setName] = useState("");
    const [courseSn, setCourseSn] = useState("");
    const [schedule, setSchedule] = useState("");
    const [isBusy, setBusy] = useState(false);
    const [actionError, setActionError] = useState(null);

    const handleSave = async () => {
        if (!name || !courseSn || !schedule) {
            setActionError("请填写完整班次信息");
            return;
        }
        setBusy(true);
        setActionError(null);
        try {
            let response = await fetch("/api/class/new", {
                method: "POST",
                headers: { "Content-Type": "application/json;charset=utf-8" },
                body: JSON.stringify({ name, course_sn: parseInt(courseSn), schedule }),
            });
            if (!response.ok) {
                let errorText = await response.text();
                setActionError(errorText);
                return;
            }
            navigate("/class/list");
        } finally {
            setBusy(false);
        }
    };

    return (
        <div className="paper">
            <div className="paper-head">
                <h3>新建班次</h3>
            </div>
            <div className="paper-body">
                <div className="field">
                    <label>班次名称：</label>
                    <input type="text" value={name} onChange={e => setName(e.target.value)} />
                </div>
                <div className="field">
                    <label>课程名称：</label>
                    <select value={courseSn} onChange={e => setCourseSn(e.target.value)}>
                        <option value="">请选择课程</option>
                        {safeCourseList.map(c => (
                            <option key={c.cou_sn} value={c.cou_sn}>{c.cou_name}</option>
                        ))}
                    </select>
                </div>
                <div className="field">
                    <label>上课时间：</label>
                    <input type="text" value={schedule} onChange={e => setSchedule(e.target.value)} placeholder="如：周一 8:00-10:00 教室101" />
                </div>
                {actionError && <div className="error">{actionError}</div>}
            </div>
            <div className="paper-footer">
                <div className="btns">
                    <button className="btn" onClick={() => navigate("/class/list")}>
                        返回
                    </button>
                    <button className="btn" onClick={handleSave} disabled={isBusy}>
                        保存
                    </button>
                </div>
            </div>
        </div>
    );
}

export default ClassNew;